package ua.com.infinite.mobile;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import ua.com.infinite.mobile.server.Constants;
import ua.com.infinite.mobile.server.DataLoaderBase;
import ua.com.infinite.mobile.server.DataLoaderLoginJoin;
import ua.com.infinite.mobile.server.OnDownloadingListener;
import ua.com.infinite.mobile.server.RequestObject;
import ua.com.infinite.mobile.utils.PhoneUtils;
import android.R.anim;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class JoinActivity extends Activity implements OnDownloadingListener, OnClickListener, OnCheckedChangeListener {
	// Const

	public static final int RETRY = 3;

	private static final int DIALOG_DATA_TRANSFER = 101;

	private String PHONE_NUMBER = "pn";
	private String SECURE_CODE = "sc";
	private String FIRS_NAME = "fn";
	private String LAST_NAME = "ln";
	private String LOGIN = "log";
	private String PASSWORD1 = "pas1";
	private String PASSWORD2 = "pas2";
	private String EMAIL = "em";
	private String DISPL_NUM = "dn";
	private String PHONE_SENDED = "ps";
	private String SECURE_APPROV = "sca";

	// Variables
	private String phoneNumber;
	private String securityCode = "";
	private String firstName;
	private String lastName;
	private String login;
	private String password;
	private String email;
	private int displayedChild = 0;

	private boolean isPhoneSended;
	private boolean isSecurytiCodeApproved;
	private boolean isPasswordShow;

	private int probeCount = 0;

	private String lastAction;

	// private InfiniteServerManager manager;
	private DataLoaderLoginJoin dataLoader;

	// UI
	private ViewFlipper flipper;

	private TextView logo1, logo2, logo3;
	private TextView phoneNumberLabel;
	private EditText phoneNumberEd;
	private EditText securityCodeEd;
	private Button btnSendPhoneNumber;
	private Button btnCheckSecurityCode;
	private Button btnCheckNames;

	private EditText firstNameEd;
	private EditText lastNameEd;
	private EditText loginEd;
	private EditText password1Ed;
	private EditText password2Ed;
	private EditText emailEd;
	private TextView passwordCheckBoxLabel;
	private CheckBox passwordCheckBox;
	private Button btnRegistrate;

	private ProgressDialog progressDialog;
	private int showedDialogId;

	private Typeface frederickaFont;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join);
		frederickaFont = Typeface.createFromAsset(getAssets(), "FrederickatheGreat.ttf");
		setupUI();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		setResult(RESULT_CANCELED);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(PHONE_NUMBER, phoneNumberEd.getText().toString());
		outState.putString(SECURE_CODE, securityCode);
		outState.putString(FIRS_NAME, firstNameEd.getText().toString());
		outState.putString(LAST_NAME, lastNameEd.getText().toString());
		outState.putString(PASSWORD1, password1Ed.getText().toString());
		outState.putString(PASSWORD2, password2Ed.getText().toString());
		outState.putString(LOGIN, loginEd.getText().toString());
		outState.putString(EMAIL, emailEd.getText().toString());
		outState.putInt(DISPL_NUM, displayedChild);
		outState.putBoolean(PHONE_SENDED, isPhoneSended);
		outState.putBoolean(SECURE_APPROV, isSecurytiCodeApproved);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		flipper.setDisplayedChild(displayedChild = savedInstanceState.getInt(DISPL_NUM));
		phoneNumberEd.setText(phoneNumber = savedInstanceState.getString(PHONE_NUMBER));
		firstNameEd.setText(firstName = savedInstanceState.getString(FIRS_NAME));
		lastNameEd.setText(lastName = savedInstanceState.getString(LAST_NAME));
		password1Ed.setText(savedInstanceState.getString(PASSWORD1));
		password2Ed.setText(savedInstanceState.getString(PASSWORD2));
		loginEd.setText(login = savedInstanceState.getString(LOGIN));
		emailEd.setText(email = savedInstanceState.getString(EMAIL));
		if (isPhoneSended = savedInstanceState.getBoolean(PHONE_SENDED)) {
			securityCodeEd.setEnabled(true);
			btnSendPhoneNumber.setVisibility(Button.GONE);
			btnCheckSecurityCode.setVisibility(Button.VISIBLE);
		}
		if (isSecurytiCodeApproved = savedInstanceState.getBoolean(SECURE_APPROV)) {
			securityCodeEd.setText(securityCode = savedInstanceState.getString(SECURE_CODE));
			securityCodeEd.setEnabled(true);
			btnSendPhoneNumber.setVisibility(Button.GONE);
			btnCheckSecurityCode.setVisibility(Button.VISIBLE);
		} else {
			securityCodeEd.setText("");
			// securityCodeEd.setEnabled(false);
			btnSendPhoneNumber.setVisibility(Button.VISIBLE);
			btnCheckSecurityCode.setVisibility(Button.GONE);
		}
	}

	/*
	 * @Override public void makeRequest(RequestObject requestObject) {
	 * lastAction = requestObject.getAction(); manager = new
	 * InfiniteServerManager(); manager.makeRequest(JoinActivity.this,
	 * requestObject); }
	 */

	/*
	 * @Override public void onPreExecute() { showDialog(DIALOG_DATA_TRANSFER);
	 * }
	 * 
	 * @Override public void onPostExecute(JSONObject object) {
	 * progressDialog.dismiss(); if (object == null) { return; } int error_id;
	 * try { error_id = object.getInt(Constants.ERROR_ID); if (error_id == 0) {
	 * if (lastAction.equals(Constants.CHECK_NUMBER)) { securityCode =
	 * object.getString(Constants.SECURYTY_CODE); isPhoneSended = true;
	 * securityCodeEd.setEnabled(true);
	 * btnSendPhoneNumber.setVisibility(Button.GONE);
	 * btnCheckSecurityCode.setVisibility(Button.VISIBLE);
	 * Toast.makeText(getBaseContext(), R.string.get_code_from_sms,
	 * Toast.LENGTH_LONG) .show(); } else if
	 * (lastAction.equals(Constants.REGISTER)) {
	 * Toast.makeText(getBaseContext(), R.string.wellcome,
	 * Toast.LENGTH_LONG).show(); Intent resultIntent = new Intent();
	 * resultIntent.putExtra(Constants.USER_LOGIN_LOGIN, login);
	 * resultIntent.putExtra(Constants.USER_LOGIN_PASSWORD, password);
	 * setResult(RESULT_OK, resultIntent); JoinActivity.this.finish(); } } }
	 * catch (JSONException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } }
	 */

	@Override
	public void startDownload(RequestObject request, boolean returnDataToCaller) {
		if (PhoneUtils.isInternetConnected(JoinActivity.this)) {
			dataLoader = new DataLoaderLoginJoin(JoinActivity.this, this, returnDataToCaller);
			dataLoader.execute(new RequestObject[] { request });
			lastAction = request.getAction();
		}

	}

	@Override
	public void onStartDownloading() {
		showDialog(DIALOG_DATA_TRANSFER);
	}

	@Override
	public void returnData(JSONObject object) {
		progressDialog.dismiss();
		try {
			if (PhoneUtils.isJSonValid(object)) {
				if (lastAction.equals(Constants.CHECK_NUMBER)) {
					securityCode = object.getString(Constants.SECURYTY_CODE);
					isPhoneSended = true;
					securityCodeEd.setEnabled(true);
					btnSendPhoneNumber.setVisibility(Button.GONE);
					btnCheckSecurityCode.setVisibility(Button.VISIBLE);
					Toast.makeText(getBaseContext(), R.string.get_code_from_sms, Toast.LENGTH_LONG).show();
				} else if (lastAction.equals(Constants.REGISTER)) {
					Toast.makeText(getBaseContext(), R.string.wellcome, Toast.LENGTH_LONG).show();
					Intent resultIntent = new Intent();
					resultIntent.putExtra(Constants.USER_LOGIN_LOGIN, login);
					resultIntent.putExtra(Constants.USER_LOGIN_PASSWORD, password);
					setResult(RESULT_OK, resultIntent);
					JoinActivity.this.finish();
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void succesDownloading(boolean isSucces) {

	}

	@Override
	public Dialog onCreateDialog(int id) {
		progressDialog = new ProgressDialog(JoinActivity.this);
		switch (id) {
		case DIALOG_DATA_TRANSFER:
			progressDialog.setMessage(getResources().getText(R.string.data_transfer));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			return progressDialog;
		default:
			return null;
		}

	}

	private void setupUI() {
		flipper = (ViewFlipper) findViewById(R.id.join_flipper);
		flipper.setInAnimation(this, anim.slide_in_left);
		flipper.setOutAnimation(this, anim.slide_out_right);

		logo1 = (TextView) findViewById(R.id.logo1);
		logo2 = (TextView) findViewById(R.id.logo2);
		logo3 = (TextView) findViewById(R.id.logo3);
		logo1.setTypeface(frederickaFont);
		logo2.setTypeface(frederickaFont);
		logo3.setTypeface(frederickaFont);

		phoneNumberLabel = (TextView) findViewById(R.id.phone_number_label);

		phoneNumberEd = (EditText) findViewById(R.id.phone_number);
		phoneNumber = PhoneUtils.getDevicePhoneNumber(getApplicationContext());
		if (phoneNumber != null) {
			phoneNumberEd.setText(phoneNumber);
		}

		securityCodeEd = (EditText) findViewById(R.id.security_code);
		securityCodeEd.setEnabled(false);

		btnSendPhoneNumber = (Button) findViewById(R.id.btn_check_phone_number);
		btnSendPhoneNumber.setOnClickListener(this);
		btnCheckSecurityCode = (Button) findViewById(R.id.btn_check_security_code);
		btnCheckSecurityCode.setVisibility(Button.GONE);
		btnCheckSecurityCode.setOnClickListener(this);

		firstNameEd = (EditText) findViewById(R.id.first_name);
		lastNameEd = (EditText) findViewById(R.id.second_name);

		btnCheckNames = (Button) findViewById(R.id.btn_check_names);
		btnCheckNames.setOnClickListener(this);

		loginEd = (EditText) findViewById(R.id.login);
		password1Ed = (EditText) findViewById(R.id.password1);
		password2Ed = (EditText) findViewById(R.id.password2);
		emailEd = (EditText) findViewById(R.id.email);

		passwordCheckBoxLabel = (TextView) findViewById(R.id.password_visibility);
		passwordCheckBox = (CheckBox) findViewById(R.id.password_visibility_check);
		passwordCheckBox.setOnCheckedChangeListener(this);

		btnRegistrate = (Button) findViewById(R.id.registrate);
		btnRegistrate.setOnClickListener(this);
	}

	@Override
	public void onClick(View paramView) {
		switch (paramView.getId()) {
		case R.id.btn_check_phone_number:
			phoneNumber = phoneNumberEd.getText().toString();
			if (PhoneUtils.isValidPhoneNumber(phoneNumber)) {
				RequestObject request = new RequestObject();
				request.setAction(Constants.CHECK_NUMBER);
				request.addParam(Constants.USER_PHONE_NUMBER, phoneNumber);
				startDownload(request, true);
			} else {
				Toast.makeText(getBaseContext(), R.string.phone_number_not_valid, Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.btn_check_security_code:

			if ((probeCount++ < RETRY) & isPhoneSended & securityCodeEd.getText().toString().equals(securityCode)) {
				phoneNumberEd.setEnabled(false);
				btnSendPhoneNumber.setVisibility(Button.GONE);
				flipper.setDisplayedChild(1);
				isSecurytiCodeApproved = true;
				displayedChild = 1;
			} else if (probeCount > RETRY) {
				Toast.makeText(getBaseContext(), R.string.get_new_code, Toast.LENGTH_LONG).show();
				isPhoneSended = false;
				securityCodeEd.setText("");
				securityCodeEd.setEnabled(false);
				btnSendPhoneNumber.setVisibility(Button.VISIBLE);
				btnCheckSecurityCode.setVisibility(Button.GONE);
				isSecurytiCodeApproved = false;
				probeCount = 0;
			} else {
				securityCodeEd.setText("");
				Toast.makeText(getBaseContext(), R.string.code_not_valid, Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.btn_check_names:
			if (firstNameEd.getText().toString().equals("")) {
				Toast.makeText(getBaseContext(), R.string.first_name_no_valid, Toast.LENGTH_LONG).show();
				break;
			} else if (lastNameEd.getText().toString().equals("")) {
				Toast.makeText(getBaseContext(), R.string.last_name_no_valid, Toast.LENGTH_LONG).show();
				break;
			} else {
				firstName = firstNameEd.getText().toString();
				lastName = lastNameEd.getText().toString();
				flipper.setDisplayedChild(2);
				displayedChild = 2;
			}
			break;

		case R.id.registrate:
			if (loginEd.getText().toString().equals("")) {
				Toast.makeText(getBaseContext(), R.string.login_no_valid, Toast.LENGTH_LONG).show();
				break;
			} else {
				login = loginEd.getText().toString();
			}
			if (password1Ed.getText().toString().equals("")) {
				break;
			} else if (!password1Ed.getText().toString().equals(password2Ed.getText().toString())) {
				Toast.makeText(getBaseContext(), R.string.passes_no_equals, Toast.LENGTH_LONG).show();
				break;
			} else {
				password = password1Ed.getText().toString();
			}
			if (!PhoneUtils.isEmailValid(emailEd.getText().toString())) {
				Toast.makeText(getBaseContext(), R.string.email_no_valid, Toast.LENGTH_LONG).show();
				break;
			} else {
				email = emailEd.getText().toString();
			}
			RequestObject request = new RequestObject();
			request.setAction(Constants.REGISTER);
			request.addParam(Constants.USER_PHONE_NUMBER, phoneNumber);
			request.addParam(Constants.USER_FIRST_NAME, firstName);
			request.addParam(Constants.USER_LAST_NAME, lastName);
			request.addParam(Constants.USER_PASSWORD, password);
			request.addParam(Constants.USER_LOGIN, login);
			request.addParam(Constants.USER_EMAIL, email);
			startDownload(request, true);

			break;
		default:
			break;
		}

	}

	@Override
	public void onBackPressed() {
		switch (displayedChild) {
		case 0:
			finish();
			break;
		default:
			displayedChild = flipper.getDisplayedChild() - 1;
			flipper.setDisplayedChild(displayedChild);
			break;
		}

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			passwordCheckBoxLabel.setText(R.string.hide_password);
			password1Ed.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			password2Ed.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
		} else {
			passwordCheckBoxLabel.setText(R.string.show_password);
			password1Ed.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
			password2Ed.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		}
		isPasswordShow = isChecked;
	}

}
